import React, {useEffect, useState} from "react";
import CircularProgress from "@material-ui/core/CircularProgress";
import TextField from "@material-ui/core/TextField";
import Autocomplete from "@material-ui/lab/Autocomplete";

const AsyncSelect = ({id, loadingMethod, getOptionLabel, ...props}) => {
    const [open, setOpen] = useState(false);
    const [options, setOptions] = useState([]);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        if (!open) {
            return undefined;
        }
        if(!loading && !options.length) {
            setLoading(true);
            loadingMethod().then(res => {
                setLoading(false);
                setOptions(res);
            }).catch(error => {
                setLoading(false);
                setOptions([]);
            });
        }
    }, [open]);

    return (
        <Autocomplete
            id={id}
            open={open}
            onOpen={() => setOpen(true)}
            onClose={() => setOpen(false)}
            loading={loading}
            options={options}
            getOptionLabel={getOptionLabel}
            renderInput={(params) => (
                <TextField
                    {...params}
                    variant="outlined"
                    InputProps={{
                        ...params.InputProps,
                        endAdornment: (
                            <React.Fragment>
                                {loading ? <CircularProgress color="inherit" size={20} /> : null}
                                {params.InputProps.endAdornment}
                            </React.Fragment>
                        ),
                    }}
                />
            )}
            onChange={props.onChange}
            {...props}
        />
    );
}

export default AsyncSelect;
